import os

from django.contrib.auth import get_user_model
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import IsAuthenticated, AllowAny

from .serializers import RegisterSerializer, UserSerializer

User = get_user_model()


class RegisterView(APIView):
    """用户注册"""
    permission_classes = [AllowAny]  # 可以省略，默认就是允许所有访问

    def post(self, request):
        serializer = RegisterSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({"msg": "注册成功"}, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class UserProfileView(APIView):
    '''获取个人信息'''
    permission_classes = [IsAuthenticated]

    def get(self, request):
        serializer = UserSerializer(request.user, context={'request': request})
        return Response(serializer.data, status=status.HTTP_200_OK)


class UpdateProfileView(APIView):
    '''更新个人信息'''
    permission_classes = [IsAuthenticated]

    def put(self, request):
        serializer = UserSerializer(request.user, data=request.data, partial=True, context={'request': request})
        if serializer.is_valid():
            serializer.save()
            return Response({"msg": "修改成功", "data": serializer.data}, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class ChangePasswordView(APIView):
    '''修改密码'''
    permission_classes = [IsAuthenticated]

    def put(self, request):
        user = request.user
        old_password = request.data.get('old_password')
        new_password = request.data.get('new_password')

        # 校验参数是否填写
        if not old_password or not new_password:
            return Response({"msg": "原密码和新密码不能为空"}, status=status.HTTP_400_BAD_REQUEST)

        # 校验旧密码是否正确
        if not user.check_password(old_password):
            return Response({"msg": "原密码不正确"}, status=status.HTTP_400_BAD_REQUEST)

        # 设置新密码（会自动加密）
        user.set_password(new_password)
        user.save()

        return Response({"msg": "密码修改成功，请重新登录"}, status=status.HTTP_200_OK)


class UploadAvatarView(APIView):
    '''上传头像并返回完整用户信息'''
    permission_classes = [IsAuthenticated]

    def post(self, request):
        avatar = request.FILES.get('avatar')
        user = request.user

        if not avatar:
            return Response({"msg": "请上传图片文件"}, status=status.HTTP_400_BAD_REQUEST)

        # 可选：限制大小和格式
        if avatar.size > 2 * 1024 * 1024:
            return Response({"msg": "图片不能大于2MB"}, status=status.HTTP_400_BAD_REQUEST)

        # 删除旧头像（如存在）
        if user.avatar and os.path.isfile(user.avatar.path):
            os.remove(user.avatar.path)

        # 保存新头像
        user.avatar = avatar
        user.save()

        # 返回完整用户信息
        serializer = UserSerializer(user, context={'request': request})
        return Response({"msg": "上传成功", "data": serializer.data}, status=status.HTTP_200_OK)
